package com.beaven.model.model.db;

import com.beaven.model.data.helper.GroupHelper;
import com.beaven.model.data.helper.MessageHelper;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.sp.Account;
import com.beaven.model.utils.DataUtil;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.ForeignKey;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import java.util.Date;
import java.util.Objects;

/**
 * author: Beaven
 * time: 2017/5/18 13:56
 *
 * 本地会话表
 */
@Table(database = AppDatabase.class) public class Session extends BaseDbModel<Session> {

  // 消息接收者Id，用户或群组
  @PrimaryKey private String id;

  // 标题，用户的名称，或者群的名称
  @Column private String title;

  // 聊天对象，默认好友
  @Column private int receiverType = Message.RECEIVER_TYPE_NONE;

  // 未读数量，当没有在当前界面时，应当增加未读数量
  @Column private int unReadCount;

  // 最后更改时间
  @Column private Date modifyAt;

  // 对应的消息，外键为Message的Id
  @ForeignKey(tableClass = Message.class) private Message message;

  public Session() {

  }

  public Session(Identify identify) {
    this.id = identify.id;
    this.receiverType = identify.type;
  }

  public Session(Message message) {
    if (message.getReceiveGroup() == null) {
      receiverType = Message.RECEIVER_TYPE_NONE;
      User other = message.getOther();
      id = other.getId();
      title = other.getName();
    } else {
      receiverType = Message.RECEIVER_TYPE_GROUP;
      id = message.getReceiveGroup().getId();
      title = message.getReceiveGroup().getName();
    }
    this.message = message;
    this.modifyAt = message.getCreateAt();
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public int getReceiverType() {
    return receiverType;
  }

  public void setReceiverType(int receiverType) {
    this.receiverType = receiverType;
  }

  public Message getMessage() {
    return message;
  }

  public void setMessage(Message message) {
    this.message = message;
  }

  public int getUnReadCount() {
    return unReadCount;
  }

  public void setUnReadCount(int unReadCount) {
    this.unReadCount = unReadCount;
  }

  public Date getModifyAt() {
    return modifyAt;
  }

  public void setModifyAt(Date modifyAt) {
    this.modifyAt = modifyAt;
  }

  @Override public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Session session = (Session) o;

    return receiverType == session.receiverType
        && unReadCount == session.unReadCount
        && DataUtil.equals(id, session.id)
        && DataUtil.equals(title, session.title)
        && DataUtil.equals(modifyAt, session.modifyAt)
        && DataUtil.equals(message, session.message);
  }

  @Override public int hashCode() {
    int result = id != null ? id.hashCode() : 0;
    result = 31 * result + receiverType;
    return result;
  }

  @Override public boolean isSame(Session oldT) {
    return DataUtil.equals(id, oldT.id) && DataUtil.equals(receiverType, oldT.receiverType);
  }

  @Override public boolean isUiContentSame(Session oldT) {
    return DataUtil.equals(this.modifyAt, oldT.modifyAt);
  }

  /**
   * 对于一条消息，提取主要部分，用于和Session进行对应
   *
   * @param message 消息Model
   * @return 返回一个Session.Identify
   */
  public static Identify createSessionIdentify(Message message) {
    Identify identify = new Identify();
    if (message.getReceiveGroup() == null) {
      identify.type = Message.RECEIVER_TYPE_NONE;
      User other = message.getOther();
      identify.id = other.getId();
    } else {
      identify.type = Message.RECEIVER_TYPE_GROUP;
      identify.id = message.getReceiveGroup().getId();
    }
    return identify;
  }

  public void refreshToNow() {
    Message message;
    if (receiverType == Message.RECEIVER_TYPE_GROUP) {
      // 刷新当前对应的群的相关信息
      message = MessageHelper.findLastWithGroup(id);
      if (message == null) {
        // 如果没有基本信息
        // 查询群
        Group group = GroupHelper.findFromLocal(id);
        if (group != null) {
          this.title = group.getName();
        }

        this.message = null;
        this.modifyAt = new Date(System.currentTimeMillis());
      } else {
        // 本地有最后一条聊天记录
        // 如果没有基本信息, 直接从Message中去load群信息
        Group group = message.getReceiveGroup();
        group.load();
        this.title = group.getName();

        this.message = message;
        this.modifyAt = message.getCreateAt();
      }
    } else {
      // 和人聊天的
      message = MessageHelper.findLastWithUser(id);
      if (message == null) {
        // 我和他的消息已经删除完成了
        // 如果没有基本信息
        // 查询人
        User user = UserHelper.findFromLocal(id);
        if (user != null) {
          this.title = user.getName();
        }

        this.message = null;
        this.modifyAt = new Date(System.currentTimeMillis());
      } else {
        // 查询人
        User other = message.getOther();
        other.load(); // 懒加载问题
        this.title = other.getName();

        this.message = message;
        this.modifyAt = message.getCreateAt();
      }
    }
    if (message != null && !DataUtil.equals(message.getSender().getId(), Account.getUserId())) {
      this.unReadCount += 1;
    }
  }

  /**
   * 会话信息提取
   * Id存储人或者群的Id
   * Type存储具体的类型（人、群）
   */
  public static class Identify {
    public String id;
    public int type;

    @Override public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      Identify identify = (Identify) o;
      return type == identify.type && (id != null ? id.equals(identify.id) : identify.id == null);
    }

    @Override public int hashCode() {
      int result = id != null ? id.hashCode() : 0;
      result = 31 * result + type;
      return result;
    }
  }
}
